import java.util.Collections;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.CircuitBreakerRetryPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;

/**
 * @author Chris
 * @date 2019/04/15 20:38
 * @since 1.0.0
 */
@Slf4j
public class TestCircuitBreakerRetryPolicy {
    private static void vpmsRetryCoupon(final String userId) {
        // 构建重试模板实例
        RetryTemplate retryTemplate = new RetryTemplate();
        // 设置重试策略，主要设置重试次数
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(5, Collections.singletonMap(Exception.class, true));
        CircuitBreakerRetryPolicy policy = new CircuitBreakerRetryPolicy(simpleRetryPolicy);
        // 设置重试回退操作策略，主要设置重试间隔时间
        FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
        fixedBackOffPolicy.setBackOffPeriod(100);
        retryTemplate.setRetryPolicy(policy);
        retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
        //RetryContext 重试操作上下文约定，统一spring-try包装
        try {
            // 由retryTemplate 执行execute方法开始逻辑执行
            retryTemplate.execute(retryContext -> {
                // 通过RetryCallback 重试回调实例包装正常逻辑逻辑，第一次执行和重试执行执行的都是这段逻辑
                boolean result = pushCouponByVpmsaa(userId);
                if (!result) {
                    throw new RuntimeException();//这个点特别注意，重试的根源通过Exception返回
                }
                return true;
            }, retryContext -> {
                // 通过RecoveryCallback 重试流程正常结束或者达到重试上限后的退出恢复操作实例
                log.info("正在重试发券::::::::::::" + userId);
                return null;
            });
        } catch (Exception e) {
            log.info("发券错误异常========" + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        vpmsRetryCoupon("43333");
    }

    private static Boolean pushCouponByVpmsaa(String userId) throws InterruptedException {
        Random random = new Random();
        int a = random.nextInt(10);
        System.out.println("a是" + a);
        TimeUnit.MILLISECONDS.sleep(500);
        return a == 8;
    }

}
